//
//  RNChatViewController.m
//  app
//
//  Created by 王宇宙 on 2017/12/25.
//  Copyright © 2017年 Facebook. All rights reserved.
//

#import "RNChatViewController.h"
#import "RNServiceDetailViewController.h"
#import "RNYxDetailViewController.h"
#import "UIColor+YZAdd.h"
#import "UIView+YZAdd.h"
#import "UIDevice+YZAdd.h"
#import "Reachability.h"
#import "RMChatServiceCardCell.h"
#import "UIImage+Resource.h"
#import "Utils.h"


@interface RNChatViewController ()

@property (nonatomic, strong) UILabel* timeLabel;
@property (nonatomic, assign) BOOL sended;
@property (nonatomic, assign) NSInteger timeOffset;
@end

@implementation RNChatViewController

-(void)viewWillAppear:(BOOL)animated{}
-(void)viewDidAppear:(BOOL)animated{}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = _yxInfo[@"nickname"];
    [self setup];
    [self fetchTimezone];
    [self.tableView registerNib:[UINib nibWithNibName:@"RMChatServiceCardCell" bundle:nil] forCellReuseIdentifier:@"serviceCard"];
  
}
- (void)setup {
  
  self.tableView.backgroundColor = [UIColor colorWithHexString:@"0xeeeeee"];
  _timeOffset = 8;
  self.showRefreshHeader = YES;
  self.delegate = self;
  self.dataSource = self;
  [self.chatBarMoreView removeItematIndex:4];
  [self.chatBarMoreView removeItematIndex:3];
  [self.chatBarMoreView removeItematIndex:1];
  if ([UIDevice currentDevice].isIphoneX) {
    self.chatToolbar.frame = CGRectMake(0, self.chatToolbar.top - 34, self.chatToolbar.width, self.chatToolbar.height);
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
  }
  
}
- (void)showLocalTime {
  
  //显示当地时间
  CGRect frame = self.tableView.frame;
  NSString *country = @"";
  if (_yxInfo[@"country"]) {
    country = _yxInfo[@"country"];
  }
  CGFloat kLocaltimeViewHeight = 30;
  CGFloat kLocaltimeViewWidth = 110 + 10 * country.length;
  UIView *backView = [[UIView alloc]init];
  backView.frame = CGRectMake(0, frame.origin.y + 10, kLocaltimeViewWidth, kLocaltimeViewHeight);
  backView.backgroundColor = [UIColor whiteColor];
  [backView addRoundedCorners:UIRectCornerTopRight|UIRectCornerBottomRight withRadii:CGSizeMake(kLocaltimeViewHeight/2, kLocaltimeViewHeight/2)];
  [self.view addSubview:backView];
  
  UIImageView* clockIv = [[UIImageView alloc]init];
  clockIv.frame = CGRectMake(10, (kLocaltimeViewHeight-10)/2, 10, 10);
  clockIv.image = [UIImage imageNamed:@"clock"];
  [backView addSubview:clockIv];
  UILabel* timeLabel = [[UILabel alloc]init];
  timeLabel.frame = CGRectMake(clockIv.right + 5, 0, kLocaltimeViewWidth-5-clockIv.right, kLocaltimeViewHeight);
  timeLabel.textColor = [UIColor colorWithHexString:@"0x666666"];
  timeLabel.font = [UIFont systemFontOfSize:10];
  [backView addSubview:timeLabel];
  _timeLabel = timeLabel;
  //定时刷新时间
  CADisplayLink* displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(refreshTime)];
  [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma MARK Action
- (void)refreshTime {
  NSString *country = @"";
  if (_yxInfo[@"country"]) {
    country = _yxInfo[@"country"];
  }
  NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
  [formatter setDateStyle:NSDateFormatterMediumStyle];
  [formatter setTimeStyle:NSDateFormatterShortStyle];
  [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:_timeOffset*3600]];
  [formatter setDateFormat:@"当地时间 HH:mm"];
  NSString* dateString = [formatter stringFromDate:[NSDate date]];
  _timeLabel.text = [NSString stringWithFormat:@"%@%@",country, dateString];

}


#pragma MARK EaseMessageViewControllerDataSource
- (id<IMessageModel>)messageViewController:(EaseMessageViewController *)viewController
                           modelForMessage:(EMMessage *)message {
  id<IMessageModel> model = nil;
  model = [[EaseMessageModel alloc]initWithMessage:message];
  
  if (model.isSender) {
    model.avatarURLPath = _ownerInfo[@"avatar"];
    model.nickname = _ownerInfo[@"nickname"];
  }else{
    model.avatarURLPath = _yxInfo[@"avatar"];
    model.nickname = _yxInfo[@"nickname"];
  }
  return model;
}

#pragma MARK EaseMessageViewControllerDelegate
- (BOOL)messageViewController:(EaseMessageViewController *)viewController didSelectMessageModel:(id<IMessageModel>)messageModel {
  
  if (messageModel.bodyType == EMMessageBodyTypeText && messageModel.message.ext) {
    NSString* tempString = messageModel.text;
    NSArray *tempList = [tempString componentsSeparatedByString:@"*-*"];
    if (tempList.count < 7) {
      return NO;
    }
    RNServiceDetailViewController *vc = [[RNServiceDetailViewController alloc]init];
    vc.linkUrl = tempList.firstObject;
    [self.navigationController pushViewController:vc animated:YES];
  }
  
  return NO;
}

- (void)messageViewController:(EaseMessageViewController *)viewController didSelectAvatarMessageModel:(id<IMessageModel>)messageModel {
  
  if (messageModel.isSender) {
    return;
  }
  NSString* tempString = _yxInfo[@"huanxin_id"];
  if (tempString.length<3) {
    return;
  }
  RNYxDetailViewController *vc = [[RNYxDetailViewController alloc]init];
  vc.yxId = [tempString substringFromIndex:2];
  [self.navigationController pushViewController:vc animated:YES];
}


#pragma MARK UITableViewDelegate

- (void)addMessageToDataSource:(EMMessage *)message progress:(id)progress {
  [super addMessageToDataSource:message progress:progress];
  if (_yxInfo[@"serviceInfo"] && !_sended) {
    [self performSelector:@selector(scroll) withObject:nil afterDelay:.25];
  }else{

  }
}
- (void)scroll{
  [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArray.count inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

  NSInteger num = [super tableView:tableView numberOfRowsInSection:section];
  return _yxInfo[@"serviceInfo"]  && !_sended ? num + 1 : num;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  
  
  if (indexPath.row == self.dataArray.count) {
    RMChatServiceCardCell *cell = [tableView dequeueReusableCellWithIdentifier:@"serviceCard" forIndexPath:indexPath];
    cell.data = _yxInfo[@"serviceInfo"];
    [cell setSendBlock:^{
      [self cellSendAction];
    }];
    return cell;
  }else{
    UITableViewCell* cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell;
  }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  if (indexPath.row == self.dataArray.count) {
    return 160;
  }else{
    CGFloat height = [super tableView:tableView heightForRowAtIndexPath:indexPath];
    return height;
  }
}

- (void)cellSendAction {
  _sended = YES;
  NSString* tempString = _yxInfo[@"huanxin_id"];
  if (tempString.length<3) {
    return;
  }
  NSString *yxId = [tempString substringFromIndex:2];
  NSDictionary *serviceInfo = _yxInfo[@"serviceInfo"];
  NSString *unit = serviceInfo[@"displayPriceUnit"]?:@"";
  NSString *title = serviceInfo[@"title"]?:@"";
  NSString *price = serviceInfo[@"displayPrice"]?:@"";
  NSString *imgUrl = serviceInfo[@"headImgUrl"]?:@"";
  NSString *style = serviceInfo[@"tourismStyle"]?:@"";
  NSString *serviceId = serviceInfo[@"serviceId"]?:@"";
 
  NSString *content = [NSString stringWithFormat:@"http://www.zuihuiyou.com/app/#/tab/dash_service-desc/%@,%@,#inside_link_to*-*%@*-*%@*-*%@*-*%@*-*%@*-*1",yxId, serviceId, title, style, price, imgUrl, unit];
  [self sendTextMessage:content withExt:@{@"key":@"value"}];
}

#pragma MARK HTTP
- (void)fetchTimezone {
  [Utils GetWithUrlStr:@"http://api.zuihuiyou.cn/api/resource/static" params:nil SuccessBlock:^(id responseObject) {
    if (![responseObject isKindOfClass:[NSDictionary class]]) {
      return ;
    }
    NSArray* timeZone =responseObject[@"timeZone"];
    NSString* country = _yxInfo[@"country"];
    if (country && country.length>0) {
      for (int i=0; i<timeZone.count; i++) {
        NSDictionary* temp = timeZone[i];
        NSLog(@"----%@",temp[@"city"]);
        if ([temp[@"city"] isEqualToString:country]) {
          _timeOffset = [temp[@"value"] integerValue];
          dispatch_async(dispatch_get_main_queue(), ^{
            [self showLocalTime];
          });
        }
      }
      
    }
   
    
  } FailureBlock:^(id error) {
//    dispatch_async(dispatch_get_main_queue(), ^{
//      [self showLocalTime];
//    });
  }];
}

@end
